/*
 * @Author: MSN
 * @Date: 2023-05-18 21:20:58
 * @LastEditTime: 2023-05-22 22:04:35
 * @LastEditors: MSN
 * @Description:
 * @FilePath: \vue3-ts-cms\src\router\index.ts
 */
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

import localCache from '@/utils/cache'

import { firstMenu } from '@/utils/map-menus'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login-index.vue')
  },
  {
    path: '/main',
    name: 'main',
    component: () => import('@/views/main/main-index.vue')
    // children: [] -> 根据userMenus来决定 -> children
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('@/views/not-found/not-found.vue')
  }
]

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

router.beforeEach((to) => {
  // 用户未登入进入登入页面
  if (to.path !== '/login') {
    const token = localCache.getCache('token')
    if (!token) {
      return '/login'
    }
  }
  // 用户http://localhost:8081/会重定向到/main然后再跳转到firstMenu.url
  if (to.path === '/main') {
    return firstMenu.url
  }
})

export default router
